package com.example.peibei.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dingtao.common.bean.HomeBannerCate;
import com.dingtao.common.bean.RefreshResult;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDFragment;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.HomeBannerCatePresenter;
import com.example.peibei.ui.activity.CateOrderActivity;
import com.example.peibei.ui.activity.CheckInActivity;
import com.example.peibei.ui.activity.SearchActivity;
import com.example.peibei.ui.adapter.HomeCateAdapter;
import com.example.peibei.ui.adapter.MyPagerAdapter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class HomeFragmentTwo extends WDFragment {
    @BindView(R.id.cate_list)
    RecyclerView cateList;
    @BindView(R.id.banner)
    MZBannerView mMZBanner;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.rl_search)
    RelativeLayout rl_search;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.slideTablaout)
    SlidingTabLayout slideTablayout;

    List<HomeBannerCate.CategoryDTO> cates;
    List<HomeBannerCate.BannerDTO> banners;
    private HomeBannerCatePresenter homeBannerCatePresenter;
    private HomeCateAdapter homeCateAdapter;
    private SPUtils spUtils;
    private OrderListFragment orderListFragment;
    private OrderListFragment orderListFragmentOne;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private String[] mTitles = {"推荐", "北京"};
    private String cityName="北京";
    private String cityCode="101010100";

    @Override
    public String getPageName() {
        return "首页Fragment";
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_two;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        cates = new ArrayList<>();
        banners = new ArrayList<>();
        spUtils = new SPUtils(getActivity(), SpConstant.USER_TOKEN);
        spUtils.putString(SpConstant.CITY_NAME, "北京");
        spUtils.putString(SpConstant.CITY_CODE, "101010100");
        cateList.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
//        homeCateAdapter = new HomeCateAdapter(cates);
        cateList.setAdapter(homeCateAdapter);
        homeBannerCatePresenter = new HomeBannerCatePresenter(new HomeCall());
        homeBannerCatePresenter.reqeust();
        orderListFragment = new OrderListFragment("0");
        orderListFragmentOne = new OrderListFragment("1");
        fragments.add(orderListFragmentOne);
        fragments.add(orderListFragment);
        MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager(), fragments, mTitles);
        viewpager.setAdapter(adapter);
        viewpager.setOffscreenPageLimit(2);
        slideTablayout.setViewPager(viewpager);
        rl_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent(SearchActivity.class);
            }
        });
        homeCateAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                HomeBannerCate.CategoryDTO data = (HomeBannerCate.CategoryDTO) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putString("caption", data.getCaption());
                bundle.putInt("id", data.getId());
                intent(CateOrderActivity.class, bundle);
            }
        });
        mMZBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int position) {
                intent(CheckInActivity.class);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        orderListFragment.updateData(cityName,cityCode);
//        orderListFragmentOne.updateDataTwo();
    }

    class HomeCall implements DataCall<HomeBannerCate> {

        @Override
        public void success(HomeBannerCate data, Object... args) {
            mMZBanner.setIndicatorVisible(false);
            mMZBanner.setPages(data.getBanner(), (MZHolderCreator<BannerViewHolder>) BannerViewHolder::new);
            mMZBanner.start();
//            homeCateAdapter.addData(data.getCategory());
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    class BannerViewHolder implements MZViewHolder<HomeBannerCate.BannerDTO> {
        private SimpleDraweeView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, HomeBannerCate.BannerDTO data) {
            // 数据绑定
//            mImageView.setImageURI(Uri.parse(data.getImageUrl()));
            Glide.with(getActivity()).load(data.getImageUrl()).into(mImageView);
        }
    }

    @OnClick({R.id.tv_address, R.id.iv_address})
    public void setAddress() {
        getLocatedCity();
    }

    private void getLocatedCity() {
        List<HotCity> hotCities = new ArrayList<>();
        hotCities.add(new HotCity("北京", "北京", "101010100"));
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));
        CityPicker.getInstance()
                .setFragmentManager(getActivity().getSupportFragmentManager())  //此方法必须调用
                .enableAnimation(true)  //启用动画效果
//                .setAnimationStyle(anim)  //自定义动画
                .setLocatedCity(new LocatedCity("北京", "北京", "101010100"))  //APP自身已定位的城市，默认为null（定位失败）
                .setHotCities(hotCities)  //指定热门城市
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        if (data != null) {
                            TextView titleView = slideTablayout.getTitleView(1);
                            titleView.setText(data.getName());
                            tv_address.setText(data.getName());
                            spUtils.putString(SpConstant.CITY_NAME, data.getName());
                            spUtils.putString(SpConstant.CITY_CODE, data.getCode());
                            orderListFragment.updateData(data.getCode(), data.getName());
                        }
                    }

                    @Override
                    public void onLocate() {
                        //开始定位，这里模拟一下定位
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //定位完成之后更新数据
                                CityPicker.getInstance()
                                        .locateComplete(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS);
                            }
                        }, 2000);
                    }
                })
                .show();
    }

    public interface IOnrefreshListener {
        void onRefresh(RefreshLayout view);
    }

    public static IOnrefreshListener listener;

    public static void setOnrefreshListener(IOnrefreshListener listener1) {
        listener = listener1;
    }

    public interface IOnloadmoreListener {
        void onLoadmore(RefreshLayout view);
    }

    public static IOnloadmoreListener listener2;

    public static void setOnloadmoreListener(IOnloadmoreListener listener1) {
        listener2 = listener1;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(RefreshResult refresh) {

    }

    @Override
    public void onPause() {
        super.onPause();
        mMZBanner.pause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
